package com.heo.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import com.heo.pub.ServerConfig;

public class RemoteUpgrade {

	private byte[] upgradeByte;
	
	public RemoteUpgrade(String firmwarePath) {
		try {
			FileInputStream ips = null;  
			File firmwareFile = FileHelper.getFile(ServerConfig.FIRMWARE_DIRECTORY + "/" + firmwarePath);
		    if (firmwareFile != null)
		    {
		    	ips = new FileInputStream(firmwareFile);  
				upgradeByte = readInputStream(ips);// 得到图片的二进制数据
		    }
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public byte[] getUpgradeByte(int start, int length) {
		byte[] lengthByte = null;
		try {
			if (start >= upgradeByte.length) {
				lengthByte = new byte[] {};
			} else {
				int sLength = upgradeByte.length - start;
				lengthByte = new byte[length];
				if (sLength >= length) {
					System.arraycopy(upgradeByte, start, lengthByte, 0, length);
				} else {
					System.arraycopy(upgradeByte, start, lengthByte, 0, sLength);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return lengthByte;
	}

	public int getUpgradeByteLength() {
		if(upgradeByte != null && upgradeByte.length > 0) {
			return upgradeByte.length;
		}
		return 0;
	}
	
	public String getCrc16() {
		if(upgradeByte != null && upgradeByte.length > 0) {
			return CRC16.crc16CcittFlase(upgradeByte);
		}
		return "";
	}

	/**
	 * 从输入流中获取数据
	 * 
	 * @param inStream
	 *            输入流
	 * @return
	 * @throws Exception
	 */
	private static byte[] readInputStream(InputStream inStream)
			throws Exception {
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = inStream.read(buffer)) != -1) {
			outStream.write(buffer, 0, len);
		}
		inStream.close();
		return outStream.toByteArray();
	}

}
